package serv

import (
	"errors"
	"github.com/gin-gonic/gin"
	"server/internal/app/model"
	"server/internal/database"
	"server/pkg/jwts"
	"server/pkg/tools"
	"time"
)

var Login = new(login)

type login struct{}

func (a login) Login(c *gin.Context, data model.User) (model.User, int, error) {

	Db := database.DB
	var Expires int
	users := model.User{}
	res := Db.Model(&users).Where("username = ?", data.Username).First(&users)
	if res.RowsAffected == 0 {
		return users, Expires, errors.New("用户不存在")
	}

	if !tools.ComparePasswords(data.Password, users.Password) {
		return users, Expires, errors.New("密码错误")
	}
	users.LastLoginIp = c.ClientIP()
	users.LastLoginTime = int(time.Now().Unix())
	Db.Model(&users).Updates(&users)

	//创建token
	tokenStr, ExpiresAt, err := jwts.Encrypt(users.ID, data.Username, users.LastLoginIp, 3)
	refreshToken, _, err := jwts.Encrypt(users.ID, data.Username, users.LastLoginIp, 12)

	userToken := model.UserToken{}
	Db.Model(&userToken).Where("user_id=?", users.ID).First(&userToken)
	userToken.Token = tokenStr
	userToken.ExpiresAt = int(ExpiresAt.Unix())
	userToken.RefreshToken = refreshToken
	if userToken.UserId == 0 {
		userToken.UserId = users.ID
		userToken.Type = "admin"
		Db.Create(&userToken)
	} else {
		Db.Where("user_id=?", users.ID).Updates(userToken)
	}

	if err != nil {
		//log.Println("token 创建失败:", err)
		return users, Expires, err
	}

	users.Token = tokenStr
	users.RefreshToken = refreshToken
	Expires = int(ExpiresAt.Unix())
	return users, Expires, nil
}

func (a login) RefreshToken(c *gin.Context, data model.User) (model.User, int, error) {

	Db := database.DB
	var Expires int
	users := model.User{}
	res := Db.Model(&users).Where("username = ?", data.Username).First(&users)
	if res.RowsAffected == 0 {
		return users, Expires, errors.New("用户不存在")
	}

	users.LastLoginIp = c.ClientIP()
	users.LastLoginTime = int(time.Now().Unix())
	Db.Model(&users).Updates(&users)

	//创建token
	tokenStr, ExpiresAt, err := jwts.Encrypt(users.ID, data.Username, users.LastLoginIp, 3)
	refreshToken, _, err := jwts.Encrypt(users.ID, data.Username, users.LastLoginIp, 12)

	userToken := model.UserToken{}
	Db.Model(&userToken).Where("user_id=?", users.ID).First(&userToken)
	userToken.Token = tokenStr
	userToken.ExpiresAt = int(ExpiresAt.Unix())
	userToken.RefreshToken = refreshToken
	if userToken.UserId == 0 {
		userToken.UserId = users.ID
		userToken.Type = "admin"
		Db.Create(&userToken)
	} else {
		Db.Where("user_id=?", users.ID).Updates(userToken)
	}

	if err != nil {
		//log.Println("token 创建失败:", err)
		return users, Expires, err
	}

	users.Token = tokenStr
	users.RefreshToken = refreshToken
	Expires = int(ExpiresAt.Unix())
	return users, Expires, nil
}
